package com.android.view.activity.user;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.model.entity.res.AccountTokenResult;
import com.android.presenter.info.AccountTokenPresenter;
import com.android.util.RequestEntityUtils;
import com.android.util.ToastUtil;
import com.android.util.WindowUtils;
import com.android.BuildConfig;
import com.android.R;
import com.android.model.entity.res.AccountInfoResult;
import com.android.model.entity.res.CreateTokenResult;
import com.android.model.entity.res.LoginResult;
import com.android.model.entity.res.UserInfoResult;
import com.android.presenter.info.AccountInfoPresenter;
import com.android.presenter.info.CreateTokenPresenter;
import com.android.presenter.info.LoginPresenter;
import com.android.presenter.info.QueryUserInfoPresenter;
import com.android.presenter.iview.IAccountInfoView;
import com.android.presenter.iview.IAccountTokenView;
import com.android.presenter.iview.ICreateTokenView;
import com.android.presenter.iview.ILoginView;
import com.android.presenter.iview.IUserInfoView;
import com.android.util.AppNecessaryUtils;
import com.android.util.HideInputUtil;
import com.android.util.SimplePrompt;
import com.android.model.info.LocalSp;
import com.android.view.activity.base.Constants;
import com.android.view.activity.base.ToolbarBaseActivity;

import butterknife.BindView;

/**
 * 注册页面
 * Created by TenFace on 2018/4/19.
 */

public class LoginActivity extends ToolbarBaseActivity implements ILoginView, IAccountTokenView, IUserInfoView, IAccountInfoView, ICreateTokenView {
    private static final String TAG = LoginActivity.class.getSimpleName();
    private Context context;

    @BindView(R.id.ivDelete)
    ImageView ivDelete;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etPWD)
    EditText etPWD;
    @BindView(R.id.tvToRegister)
    TextView tvToRegister;
    @BindView(R.id.tvResetPWD)
    TextView tvResetPWD;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.hideShowPassword)
    CheckBox hideShowPassword;
    private LoginPresenter loginPresenter;
    private QueryUserInfoPresenter queryUserInfoPresenter;
    private AccountInfoPresenter accountInfoPresenter;
    private AccountTokenPresenter accountTokenPresenter;
    private CreateTokenPresenter createTokenPresenter;
    private String accountToken;

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initView() {
        context = this;
        int color = getResourceColor(R.color.white);
        setStatusBarColor(color, 0);
        setStatusBarMode(true);
    }

    @Override
    protected void obtainData() {
        loginPresenter = new LoginPresenter(this);
        queryUserInfoPresenter = new QueryUserInfoPresenter(this);
        accountInfoPresenter = new AccountInfoPresenter(this);
        accountTokenPresenter = new AccountTokenPresenter(this);
        createTokenPresenter = new CreateTokenPresenter(this);
    }

    @Override
    protected void initEvent() {

        tvResetPWD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(context, ResetPasswordActivity.class);
                startActivity(intent);
            }
        });

        hideShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    etPWD.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPWD.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });

        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPhone.setText("");
            }
        });
        tvToRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String accountPhone = etPhone.getText().toString();
                String accountPWD = etPWD.getText().toString();
                if (accountPhone.length() != 11) {
                    ToastUtil.show("请输入正确的手机号码！");
                } else {
                    if (etPWD.getText().length() < 8) {
                        ToastUtil.show("请输入正确的密码！");
                    } else {
                        btnLogin.setClickable(false);
                        SimplePrompt.getIntance().showLoadingMessage(LoginActivity.this, "登陆中...", false);
                        loginPresenter.getLoginStatus(accountPhone, accountPWD, "PHONE");
                    }
                }
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Constants.activityList.put(TAG, this);
    }

    @Override
    public void loginSuccess(LoginResult loginResult) {
        btnLogin.setClickable(true);
        String ssoToken = loginResult.getToken();
        if (!TextUtils.isEmpty(ssoToken)) {
            Log.e("registerSuccess", "登陆成功>>>>>>>" + loginResult.getExpiredTime() + ">>>>>token=" + ssoToken);
            LocalSp.getInstance(context).saveSSOToken(ssoToken);
            accountTokenPresenter.createAccountToken(context, ssoToken);
            queryUserInfoPresenter.getUserInfo(ssoToken);

        } else {
            ToastUtil.show(loginResult.getMessage());
            SimplePrompt.getIntance().dismiss();
        }
    }

    @Override
    public void loginFail(int status, String desc) {
        btnLogin.setClickable(true);
        SimplePrompt.getIntance().dismiss();
        ToastUtil.show(desc + "请稍后重试！");
        Log.e("registerSuccess", "请求失败");
    }

    @Override
    public void queryUserInfoSuccess(UserInfoResult userInfoResult) {

    }

    @Override
    public void queryUserInfoFail(int status, String desc) {
        SimplePrompt.getIntance().dismiss();
    }

    @Override
    public void createAccountTokenSuccess(AccountTokenResult accountTokenResult) {
        ToastUtil.show("登陆成功，获取用户信息成功！");
        if (accountTokenResult != null) {
            accountToken = accountTokenResult.getValue();
            Log.e("createAccountToken", ">>>>>>>" + ">>>>>token：" + accountToken);
            LocalSp.getInstance(context).saveAccountToken(accountToken);
            accountInfoPresenter.queryAccountInfo(getContext(), accountToken);
        }
    }

    @Override
    public void createAccountTokenFail(int status, String desc) {
        SimplePrompt.getIntance().dismiss();
    }

    @Override
    public void getAccountInfoSuccess(AccountInfoResult accountInfoResult) {
        createTokenPresenter.createToken(getContext(), accountInfoResult.getAccountId(), "ORDER", accountToken);
    }

    @Override
    public void getAccountInfoFail(int status, String desc) {
        SimplePrompt.getIntance().dismiss();
    }

    @Override
    public void createTokenSuccess(CreateTokenResult createTokenResult) {
        SimplePrompt.getIntance().dismiss();
        finish();
    }

    @Override
    public void createTokenFail(int status, String desc) {
        SimplePrompt.getIntance().dismiss();
        finish();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (HideInputUtil.isShouldHideInput(v, ev)) {
                if (HideInputUtil.hideInputMethod(this, v)) {
//                    return true; //隐藏键盘时，其他控件不响应点击事件,注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 获取手机信息
     *
     * @param context context
     * @return 手机信息
     */
    private RequestEntityUtils.OsEntity getOsEntity(Context context) {
        RequestEntityUtils.OsEntity osEntity = new RequestEntityUtils.OsEntity();
        osEntity.osType = "ANDROID";
        osEntity.osVersion = android.os.Build.VERSION.RELEASE;
        osEntity.resolution = WindowUtils.getScreenWidth(context) + "*" + WindowUtils.getScreenHeight(context);
        osEntity.appVersion = BuildConfig.VERSION_CODE + "";
        String machineImEi = AppNecessaryUtils.getUUId(context);

        if (!TextUtils.isEmpty(machineImEi)) {
            osEntity.deviceId = machineImEi;
        }

        String localIpAddress = AppNecessaryUtils.getLocalIpAddress();
        if (!TextUtils.isEmpty(localIpAddress)) {
            osEntity.ip = localIpAddress;
        }

        return osEntity;
    }

}
